#include "dialog.h"
#include "ui_kiosk.h"

#include <QTableView>
#include <QSqlTableModel>
#include <QtGui>
#include <QtSql>
#include <QtDebug>
#include <QDateTime>
#include <QTimer>

bool notime;
int  fake;

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);


    db = QSqlDatabase::addDatabase( "QSQLITE" );

    db.setDatabaseName("../xyz.db");

    if ( !db.open() )
    {
        qDebug() << db.lastError();
        qDebug() << "Error: Unable to connect due to above error";
//        exit(1);
    }



    ui->ballotBox->setDisabled(true); // disables the submit


    connect(ui->loginButton, SIGNAL(pressed()), this, SLOT(login()));

}

Dialog::~Dialog()
{
    db.close();

    delete ui;
}

void Dialog::login()
{
    fake = 0;
    notime = false;


    int matchfound = 0;

    QSqlQuery q("SELECT * FROM voters");

    while ( q.next() )
    {

        if((ui->usernameLineEdit->text() == q.value(0).toString()) && (ui->pinLineEdit->text() == q.value(1).toString()))
        {

            QSqlQuery Com;
            Com.prepare("SELECT * FROM candidates");
            Com.exec();
            int index = -1;

            while(Com.next())
            {
                    index++;
                    ui->comboBox->insertItem(index, Com.value(0).toString());
            }

            matchfound = 1;
            fake++;

            ui->authenticationBox->setDisabled(true);
            ui->ballotBox->setEnabled(true);

            // keeps time for stamp
            timecount = new QTimer(this);
            connect(timecount, SIGNAL(timeout), this, SLOT(finishingTime()));
            timecount->start(60000);

            connect(ui->submitButton, SIGNAL(clicked()), this, SLOT(submit()));

        }
    }

    if (matchfound == 0)
    {
        QApplication::beep();
        ui->usernameLineEdit->clear();
        ui->pinLineEdit->clear();
    }

//    connect(ui->submitButton, SIGNAL(pressed()), this, SLOT(submit()));



}

void Dialog::submit()
{
    fake--;

    QSqlQuery user;

    user.prepare("SELECT * FROM ballots WHERE username = :name");
    user.bindValue(":name", ui->usernameLineEdit->text());

    user.exec();

    user.next();

    if(user.value(1).isNull())
    {
        QSqlQuery voteup;

        voteup.prepare("INSERT INTO ballots (timestamp, username, candidate) VALUES(:timestamp, :username, :vote)");
        voteup.bindValue(":timestamp", QDateTime::currentDateTime().toString());
        voteup.bindValue(":username", ui->usernameLineEdit->text());
        voteup.bindValue(":vote", ui->comboBox->currentText());
        voteup.exec();

        QSqlQuery numvote;
        numvote.prepare("SELECT totalvotes FROM candidates WHERE candidate = :name");
        numvote.bindValue(":name", ui->comboBox->currentText());
        numvote.exec();
        numvote.next();
        int count = numvote.value(0).toInt();
        count++;

        QSqlQuery cand;
        cand.prepare("UPDATE candidates SET totalvotes = :count WHERE candidate = :choice");
        cand.bindValue(":count", count);
        cand.bindValue(":choice", ui->comboBox->currentText());
        if (!cand.exec())
           {
               qDebug() << cand.lastError();
           }

    }


    ui->usernameLineEdit->clear();;
    ui->pinLineEdit->clear();
    ui->comboBox->clear();
    ui->authenticationBox->setEnabled(true);
    ui->ballotBox->setDisabled(true);

}

void Dialog::finishingTime()
{
    notime = true;
    timecount->stop();

    QSqlQuery first;
    first.prepare("SELECT * FROM ballots WHERE username = :name");
    first.bindValue(":name", ui->usernameLineEdit->text());
    first.exec();

    first.next();
    if(first.value(1).isNull())
    {
        QSqlQuery blank;
        blank.prepare("INSERT INTO ballots (timestamp, username, candidate) VALUES(:timestamp, :username, '')");
        blank.bindValue(":timestamp", QDateTime::currentDateTime().toString());
        blank.bindValue(":username", ui->usernameLineEdit->text());
        blank.exec();
    }

}
